import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * 任务拆分 分治 线程池
 *
 * @author 管子
 * @date 2025/5/4 9:55
 * @description: TestForkJoin 类
 */
@Slf4j
public class TestForkJoin {

    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool(4);
        System.out.println(pool.invoke(new MyTask(5)));
    }

}

@Slf4j
// 需要继承递归任务 如果没有返回结果则可以继承RecursiveAction
class MyTask extends RecursiveTask<Integer> {

    private int n;

    public MyTask(int n) {
        this.n = n;
    }

    @Override
    public String toString() {
        return "MyTask{" +
                "n=" + n +
                '}';
    }

    @Override
    protected Integer compute() {
        // 终止条件
        if (n == 1) {
            log.info("join() {}", n);
            return 1;
        }
        MyTask t1 = new MyTask(n - 1);
        t1.fork(); // 拆分，让另一个线程去执行该任务
        log.info("fork() {} + {}", n, t1);

        int result = n + t1.join();
        log.info("join() {} + {} = {}", n, t1, result);
        return result;
    }
}
